package com.reggie.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.reggie.common.BaseContext;
import com.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 1. 获取本次URI
        String requestURI = req.getRequestURI();
        // 2. 定义不需要处理的路径，遇到这些路径直接放行
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean matchResult = check(urls, requestURI);
        if(matchResult) {
            filterChain.doFilter(req, resp);
            log.info("拦截到的请求:" + requestURI + "放行");
            return ;
        }

        Object employ = req.getSession().getAttribute("employee");
        // 3. 需要处理的路径，看看登陆没
        if(employ != null) {
            log.info("拦截到的请求:" + requestURI + "放行");
            BaseContext.setCurrentId((Long) employ);
            filterChain.doFilter(req, resp);
            return;
        }

        Object user = req.getSession().getAttribute("user");
        // 3.2 需要处理的路径，看看登陆没
        if(user != null) {
            log.info("拦截到的请求:" + requestURI + "放行");
            BaseContext.setCurrentId((Long) user);
            filterChain.doFilter(req, resp);
            return;
        }

        // 4. 如果没有登陆，返回R对象，前端会重定向
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截到的请求:" + requestURI + "不放行");
    }
    public boolean check(String urls[], String URI) {
        for(String url: urls) {
            if(PATH_MATCHER.match(url, URI)) return true;
        }
        return false;
    }
}
